﻿using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace ImageServer.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class VideoController(ApplicationDbContext context, IWebHostEnvironment hostingEnvironment) : ControllerBase
    {
        private const long MaxFileSize = 100 * 1024 * 1024;//100MB
        [RequestFormLimits(MultipartBodyLengthLimit = MaxFileSize)]
        [HttpPost("upload")]
        public async Task<IActionResult> UploadVideo(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return BadRequest("No file uploaded.");
            }
            if (file.Length > MaxFileSize)
            {
                return BadRequest("File size exceeds the limit.");
            }
            if (!IsValidFileType(file.FileName))
            {
                return BadRequest("Only Video files are allowed.");
            }
            var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
            if (userIdClaim == null)
            {
                return Unauthorized("User ID not found.");
            }
            string Author = userIdClaim.Value;
            string generatedVideoId = Guid.NewGuid().ToString();
            var filePath = Path.Combine(hostingEnvironment.ContentRootPath, "Videos", generatedVideoId + ".mp4");
            if (!Directory.Exists(Path.Combine(hostingEnvironment.ContentRootPath, "Videos")))
            {
                Directory.CreateDirectory(Path.Combine(hostingEnvironment.ContentRootPath, "Videos"));
            }
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            var video = new Video
            {
                Id = generatedVideoId,
                Title = file.FileName,
                Description = "",
                Author = Author,
                FilePath = filePath,
                UploadTime = DateTime.Now,
                PlayCount = 0,
                LikeCount = 0
            };

            context.Video.Add(video);
            context.SaveChangesAsync();

            return Ok("video uploaded successfully.");
        }

        private bool IsValidFileType(string fileName)
        {
            var allowedExtensions = new[] { ".mp4", ".avi", ".mp3", ".wav" };
            var extension = Path.GetExtension(fileName).ToLower();
            return allowedExtensions.Contains(extension);
        }
    }
}

